<template>
  <div class="page-mobile_certificate">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="证书查询"
    ></white-header>
    <van-form @submit="searchCertificate">
        <van-field
            readonly
            clickable
            name="picker"
            :value="typeValue"
            label="查询类型"
            placeholder="点击选择查询类型"
            @click="showPicker = true"
        />
        <van-field
            v-model="form.name"
            name="姓名"
            label="姓名"
            placeholder="请输入姓名"
            v-if="form.type == 2"
        />
        <van-field
            v-model="form.idNumber"
            type="text"
            name="身份证"
            label="身份证"
            placeholder="请输入身份证"
            v-if="form.type == 2"
        />
        <van-field
            v-model="form.certificateNo"
            type="text"
            name="证书编号"
            label="证书编号"
            placeholder="请输入证书编号"
            v-if="form.type == 1"
        />
        <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">查询</van-button>
        </div>
        </van-form>
        <div class="certificate-list">
            <div class="certificate-item" v-for="(item, index) in certificateList" :key="index">
                <div class="certificate-left">
                    <p>姓&emsp;&emsp;名：{{ item.name }}</p>
                    <p>证书编号：{{ item.certificateNo }}</p>
                    <p>证书类型：{{ item.certificateTypeName }}</p>
                </div>
                <!-- <div class="certificate-right" @click="previewFile(item.url, item.certificateNo)">预览</div> -->
                <div class="certificate-right" @click="downloadExport(item.url, item.certificateNo)">下载</div>
            </div>
        </div>
        <van-popup v-model="showPicker" position="bottom">
            <van-picker
                show-toolbar
                value-key="text"
                :columns="columns"
                @confirm="onConfirm"
                @cancel="showPicker = false"
            />
        </van-popup>
        <div class="preview-file-dialog" v-if="previewFileDialog">
        
        <client-only>
          <pdf
              class="preview-pdf"
              v-if="previewFileType == 1 && previewFileUrl"
              ref="pdf"
              :src="previewFileUrl"
          >
          </pdf>
        </client-only>
        <!-- <pdf
            class="preview-pdf"
            v-if="previewFileType == 1 && previewFileUrl"
            ref="pdf"
            :src="previewFileUrl"
            :page="currentPage"
            @num-pages="pageCount = $event"
            @page-loaded="currentPage = $event"
            @loaded="loadPdfHandler"
        >
        </pdf> -->
        <!-- <iframe v-if="previewFileType == 1" :src="previewFileUrl" frameborder="0" style="width: 100%; height: 100%;margin-top:1rem"></iframe> -->
        <!-- <object class="preview-pdf" v-if="previewFileType == 1" :data="previewFileUrl" type="application/pdf">
          <iframe v-if="previewFileType == 1" :src="previewFileUrl" frameborder="0" style="width: 100%; height: 100%;margin-top:1rem"></iframe>
        </object> -->
        <p class="preview-arrow" v-if="previewFileType == 1">
            <span
            @click="changePdfPage(0)"
            class="turn"
            :class="{ grey: currentPage == 1 }"
            >上一页</span
            >
            <span style="margin:0 20px;">{{ currentPage }} / {{ pageCount }}</span>
            <span
            @click="changePdfPage(1)"
            class="turn"
            :class="{ grey: currentPage == pageCount }"
            >下一页</span
            >
        </p>
        <img
            class="preview-img"
            v-if="previewFileType == 2"
            :src="previewFileUrl"
            alt=""
        />
        <Icon type="md-close close-preview" @click="previewFileDialog = false" />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { downloadReport, searchCertificate } from "~/api/course";
export default {
  name: "certificate",
  components: {
    WhiteHeader,
  },
  data() {
    return {
        currentPage: 0, // pdf文件页码
        pageCount: 0, // pdf文件总页数
        pdfPages: 0, //pdf页数
        vuePdf: null, //vue-pdf对象
        previewFileDialog: false, //预览窗口弹窗
        previewFileType: 1, //1:pdf 2:文件
        // 预览文件地址
        previewFileUrl: null,
         typeValue:"编号查询",
         columns: [{id:1,text:"编号查询"},{id:2,text:"身份查询"}],
         showPicker: false,
         form:{
             type:1
         },
         certificateList:[]
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      }
    })
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      // console.log(val)
      if (val === 0 && this.currentPage > 1) {
        // this.currentPage--;
        this.$nextTick(() => {
          this.currentPage--;
        });
        // console.log(this.currentPage)
      }
      if (val === 1 && this.currentPage < this.pageCount) {
        this.$nextTick(() => {
         this.currentPage++;
        });
        // this.currentPage++;
        // console.log(this.currentPage)
      }
    },

    // pdf加载时
    loadPdfHandler(e) {
      console.log("加载pdf",e);
      this.$nextTick(() => {
        this.currentPage = 1; // 加载的时候先加载第一页
      });
    },
    // 证书预览
    async previewFile(url, certificateNo) {
      if (/\.pdf/.test(url)) {
        console.log("是pdf文件");
        this.previewFileType = 1;
        this.previewFileUrl = url;
        let CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/"
        let loadingTask = this.vuePdf.default.createLoadingTask({
          url: url,
          cMapUrl: CMAP_URL,
          cMapPacked: true,
        });
        console.log(loadingTask.promise);
        let res = await loadingTask.promise;
        // this.previewFileUrl = loadingTask;
        this.pdfPages = res._pdfInfo.numPages;
        this.pageCount = res._pdfInfo.numPages;
        console.log(res._pdfInfo);
        // loadingTask.promise.then(pdf => {
        //     this.pdfPages = pdf.numPages;
        //     this.pageCount = pdf.numPages;
        //   }).catch(err => {
        //     console.error("pdf 加载失败", err);
        //   });
      } else {
        console.log("是图片");
        this.previewFileType = 2;
        this.previewFileUrl = url;
      }

      // this.previewFileUrl = url;
      this.previewFileDialog = true;
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
          time = parseInt(time);
        } else if (typeof time === "string") {
          time = time.replace(new RegExp(/-/gm), "/");
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return time_str;
    },
    onConfirm(value) {
      this.typeValue = value.text;
      this.form.type = value.id;
      if (value.id == 1) {
        this.form.name = "";
        this.form.idNumber = "";
      } else {
        this.form.certificateNo = "";
      }
      this.showPicker = false;
    },
    //证书下载
    async downloadExport(url, reportName) {
      this.SET_IS_LOADING(true);

      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = reportName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    async searchCertificate() {
      let params = {};
      if (this.form.type == 1) {
        if (!(this.form.certificateNo && this.form.certificateNo.trim())) {
            this.$toast({
                message: '请填写证书编号',
                icon: 'warn-o',
            });
          return;
        }
        if (!/^[0-9a-zA-Z_\-\.]{1,}$/.test(this.form.certificateNo)) {
            this.$toast({
                message: '请输入正确的证书编号',
                icon: 'warn-o',
            });
          return;
        }
        params = {
          certificateNo: this.form.certificateNo
        };
      } else {
        if (!(this.form.name && this.form.name.trim())) {
            this.$toast({
                message: '请填写姓名',
                icon: 'warn-o',
            });
          return;
        }
        if (!this.form.idNumber) {
            this.$toast({
                message: '请填写身份证',
                icon: 'warn-o',
            });
          return;
        }
        if (
          !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            this.form.idNumber
          )
        ) {
            this.$toast({
                message: '请输入正确的身份证',
                icon: 'warn-o',
            });
          return;
        }
        params = {
          name: this.form.name,
          idNumber: this.form.idNumber
        };
      }
      this.SET_IS_LOADING(true);
      let result = await searchCertificate(params);
      if (result && result.data && result.data.code == 200) {
        this.certificateList = result.data.data;
        if(result.data.data.length > 0){
          this.$toast({
              message: '查询成功',
              icon: 'passed',
          });
        }else{
          this.$toast({
              message: '没有查询到证书哟',
              icon: 'passed',
          });
        }
        
      } else {
        
      }
      this.SET_IS_LOADING(false);
    },
  },
  activated() {},
  deactivated() {},
  destroyed() {},
  created() {
      if (process.client) {
        this.vuePdf = require('vue-pdf')
      }
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile_certificate {
  width: 7.2rem;
  min-height: 100vh;
  background-color: #f2f3f5;
  .preview-file-dialog {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 7.2rem;
    height: 100%;
    background: #fff;
    z-index: 10000000000000000;
    overflow: auto;
    .preview-btn {
      font-size: .3rem;
      cursor: pointer;
      color: var(--theme-color);
    }
    .close-preview {
      position: fixed;
      right: .3rem;
      top: .3rem;
      font-size: .6rem;
      cursor: pointer;
    }
    .preview-img {
      position: absolute;
      left: 0;
      // top: 0;
      right: 0;
      // bottom: 0;
      padding: .3rem 0;
      max-width: 6.9rem;
      margin: auto;
    }
    .preview-pdf {
      width: 7.2rem;
      margin: 0 auto;
    }
    .preview-arrow {
      padding: .3rem 0;
      text-align: center;
      font-size: .3rem;
      .turn {
        cursor: pointer;
      }
    }
  }
  .certificate-list{
      margin-top: 1rem;
      .certificate-item{
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 7.2rem;
          box-sizing: border-box;
          background: #ffffff;
          font-size: .3rem;
          border-bottom: 1px solid #e6e6e6;
          padding: .1rem;
          &:last-child {
            border-bottom: none;
          }
          .certificate-left{
              width: 80%;
              p{
                  margin: .1rem 0;
              }
          }
          .certificate-right{
              width: 20%;
              text-align: center;
              color: var(--theme-color);
          }
      }
  }
}
</style>
<style lang="scss">
.page-mobile_certificate {
}
</style>
